package scm.chyeung23.mtr;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Matrix;
import android.graphics.PointF;
import android.os.Bundle;
import android.util.FloatMath;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;




public class MTR extends Activity implements OnTouchListener {
	/** Called when the activity is first created. */

	// Variables for touch
	private final int NONE = 0;
	private final int DRAG = 1;
	private final int ZOOM = 2;
	private int mode = NONE;
	
	// for drag & zoom
	Matrix M_new = new Matrix();
	Matrix M = new Matrix();

	PointF p1 = new PointF();

	private PointF pivot;
	private float dist_old;
	
	
	TextView textView;
	MyImageView MTRView;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		
		textView = (TextView)findViewById(R.id.system_map_from);
		MTRView = (MyImageView) findViewById(R.id.system_map_view);
		
		Station newSation = new Station("Kwai Hing");
		newSation.setGolPos(new PointF(166f, 40f));		
		MTRView.addStation(newSation);

		MTRView.setOnTouchListener(this);
		
	}
	
	public boolean onTouch(View v, MotionEvent event) {
		
		switch (event.getAction() & MotionEvent.ACTION_MASK) {
		case MotionEvent.ACTION_DOWN:

			mode = DRAG; // start to drag

			p1.set(event.getX(), event.getY());
			M.set(((ImageView) v).getImageMatrix());
			break;
		case MotionEvent.ACTION_POINTER_DOWN: // for pinching
			mode = ZOOM;

			dist_old = spacing(event);
			pivot = midPoint(event);
			M.set(((ImageView) v).getImageMatrix());
			break;
		case MotionEvent.ACTION_MOVE:
			if (mode == DRAG) {
				M_new.set(M);
				// p2 = (e.getX(), e.getY())
				M_new.postTranslate(event.getX() - p1.x, event.getY() - p1.y);

				((ImageView) v).setImageMatrix(M_new);
			} else if (mode == ZOOM) {
				float scale = spacing(event) / dist_old;
				M_new.set(M);
				M_new.postScale(scale, scale, pivot.x, pivot.y);

				((ImageView) v).setImageMatrix(M_new);
			}
			break;
		case MotionEvent.ACTION_POINTER_UP:
		case MotionEvent.ACTION_UP:
			mode = NONE;

			// simulate onClick event
			if (event.getAction() == MotionEvent.ACTION_UP) {

				// we check if positions for touch down/up are close enough,
				// since in practice,
				// it is almost impossible to make finger down & up happen at
				// same position

				// if (dist_squared < 100)
				// {
				onClickEvent(event); // to be defined
				// }
			}

			break;
		}
		
		
		return true;
		
	}

	private float spacing(MotionEvent event) {
		/** Determine the space between the first two fingers */
		
			float x = event.getX(0) - event.getX(1);
			float y = event.getY(0) - event.getY(1);
			return FloatMath.sqrt(x * x + y * y);
	}

	/** Calculate the mid point of the first two fingers */
	private PointF midPoint(MotionEvent event) {
		return new PointF((event.getX(0) + event.getX(1)) * 0.5f, (event
				.getY(0) + event.getY(1)) * 0.5f);
	}
	
	private void onClickEvent(MotionEvent event) {

		// convert position in device coordinate to image coordinate
		PointF Lpt = DPtoLP(new PointF(event.getX(), event.getY()));
		PointF tStationPos;
		Toast.makeText(this, "MouseX:" + Lpt.x + "\nMouseY:"+Lpt.y, Toast.LENGTH_SHORT).show();
		
		
		for (int i = 0; i < MTRView.getMyStations().size(); i++) {

			tStationPos = MTRView.getMyStations().get(i).getGolPos(); 
			

			float dist_squared = (Lpt.x - tStationPos.x)*(Lpt.x - tStationPos.x)
									+ (Lpt.y - tStationPos.y)*(Lpt.y - tStationPos.y);
			// if (rect.contains(Lpt.x, Lpt.y))
			if (dist_squared < MTRView.getRadius4Stations() * MTRView.getRadius4Stations()) {
				showDislog(MTRView.getMyStations().get(i),i);
				// reset matrix, since it is a click event.
				// no dragging/zooming is needed
				MTRView.setImageMatrix(M);
			}
			

		}

	}
	
	private void showDislog(final Station station,final int index) {

		final CharSequence[] items = { "From " + station.getName(), "To " + station.getName()};
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		//builder.setTitle("Pick a color");
		builder.setItems(items, new DialogInterface.OnClickListener() 
		{
			public void onClick(DialogInterface dialog, int item) 
			{
				Toast.makeText(MTR.this, items[item],Toast.LENGTH_SHORT).show();

				TextView textView = (TextView)findViewById(R.id.system_map_from);
				
				//Toast.makeText(MyImageView.this.getContext(), textView.set,Toast.LENGTH_SHORT).show();
				if(textView!=null)
				{
					textView.setText(station.getName());
					Toast.makeText(MTR.this, textView.getText(),Toast.LENGTH_SHORT).show();
				}
				else
				{
					Toast.makeText(MTR.this, "textView is null",Toast.LENGTH_SHORT).show();
				}
			}
		});
		AlertDialog alert = builder.create();
		alert.show();
	}
	
	// convert device coordinates to logical(image) coordinates
	public PointF DPtoLP(PointF pt) {
		Matrix matrix = MTRView.getImageMatrix();
		Matrix inverse = new Matrix();

		if (matrix.invert(inverse)) { // if matrix inverse exists
			float[] pts = new float[2];
			pts[0] = pt.x;
			pts[1] = pt.y;
			inverse.mapPoints(pts);

			return new PointF(pts[0], pts[1]);
		}

		return pt; // in case the inverse of the matrix doesn't exist
	}

}